/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-06-01 18:58:45
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message, Modal } from 'antd';
import {
  ADD_AT_TYPE,
  ARC_TYPE_LOADING,
  DELETE_AT_TYPE,
  HIDE_ADD_DIALOG,
  SET_ARC_TYPE_LIST,
  SET_SELECT_FOND,
  SHOW_ADD_DIALOG,
  UPDATE_AT_REPO
} from '../constants';
import { ArcTypeReducer } from '../reducers/ArcTypeReducer';
import {
  addArchiveType,
  createAtRepo,
  deleteArchiveType,
  editArchiveType,
  fetchATListByFondId
} from '@/api/archivesType';
import { useMetadataRouterTypeContext } from '@/view/system/Metadata/contexts/MetadataRouterTypeContext';
import { useArcTypeRouterTypeContext } from '@/view/system/ArcType/contexts/ArcTypeRouterTypeContext';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  // 库及层级相关信息
  repoInfo: {},

  ATList: []
};

const ArcTypeContext = createContext();

const ArcTypeContextProvider = (props) => {
  const { routerType } = useArcTypeRouterTypeContext();
  const [state, dispatch] = useReducer(ArcTypeReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 获取全部档类型列表
     */
    async fetchArcList(id) {
      dispatch({ type: ARC_TYPE_LOADING });
      const res = await fetchATListByFondId(id, routerType);
      const { data } = res;
      dispatch({ type: SET_ARC_TYPE_LIST, data });
    },

    setATList(data) {
      dispatch({ type: SET_ARC_TYPE_LIST, data });
    },

    /**
     * @description: 打开新增档案类型弹窗
     */
    showDialog() {
      dispatch({ type: SHOW_ADD_DIALOG });
    },

    /**
     * @description: 关闭新增档案类型弹窗
     */
    hideDialog() {
      dispatch({ type: HIDE_ADD_DIALOG });
    },

    /**
     * @description: 增加档案类型
     * @param {*} data 档案类型Obj
     */
    addAtType(data) {
      data.fondsId = state.selectFond.id;
      return new Promise((resolve, reject) => {
        addArchiveType(data)
          .then((res) => {
            dispatch({ type: ADD_AT_TYPE, data: res.data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 编辑档案类型
     * @param {*} params 档案类型Obj
     */
    editAtType(params) {
      return new Promise((resolve, reject) => {
        editArchiveType(params)
          .then((res) => {
            const { data } = res;
            message.success('编辑成功');
            // dispatch({ type: ADD_AT_TYPE, data: res.data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 增加档案类型
     * @param {*} id 档案类型Obj
     */
    deleteAtType(id) {
      Modal.confirm({
        title: '删除',
        content: '确认删除该档案类型？',
        onOk() {
          deleteArchiveType(id).then((res) => {
            const ids = res.data;
            dispatch({ type: DELETE_AT_TYPE, ids });
          });
        },
        onCancel() {
          console.log('del unit Cancel');
        }
      });
    },

    /**
     * @description: 创建档案库
     * @return {*}
     */
    createAtRepoFunc(params) {
      return new Promise((resolve, reject) => {
        createAtRepo(params)
          .then((res) => {
            console.log(res.data);
            const { data } = res;
            dispatch({ type: UPDATE_AT_REPO, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    }
  };

  useEffect(() => {
    if (state.selectFond?.id) {
      actions.fetchArcList(state.selectFond.id);
    }
  }, [state.selectFond]);

  return (
    <ArcTypeContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </ArcTypeContext.Provider>
  );
};

export const useArcTypeContext = () => {
  return useContext(ArcTypeContext);
};

export { ArcTypeContext, ArcTypeContextProvider };
